#!/bin/ksh

if [[ $# -ne 2 ]]
then echo "Usage: $0 last_year(2007)  GHCN.CL"
     exit ; fi

fortran_compile=$FC
if [[ $FC = '' ]]
then echo "set an environment variable FC to the fortran_compile_command like f90"
     echo "or do all compilation first and comment the compilation lines"
     exit
fi

infile=to_next_step/Ts.txt ; label=$2 ; last_year=$1

echo "converting text to binary file"
  rm -f Ts.txt ; ln -s $infile Ts.txt
  ${fortran_compile} text_to_binary.f -o text_to_binary.exe ; text_to_binary.exe $last_year

echo "breaking up Ts.bin into 6 zonal files"
  ${fortran_compile} split_binary.f -o split_binary.exe ; split_binary.exe

echo "trimming Ts.bin1-6"
  ${fortran_compile} trim_binary.f -o trim_binary.exe ; trim_binary.exe

for i in 1 2 3 4 5 6
do  mv Ts.bin${i}.trim Ts.${label}.$i
done

rm -f Ts.bin Ts.txt

echo "preparations for urban adjustment"
  ln -s input_files/v2.inv  .
  ${fortran_compile} invnt.f -o invnt.exe ; ./invnt.exe Ts.${label} > Ts.${label}.station.list
echo 'adding population-flag and country code to station list'
  ${fortran_compile} reformat_inv.f -o reformat_inv.exe ; reformat_inv.exe
  ./addpopcc Ts.${label}.station.list
  cp -p Ts.${label}.station.list.x Ts.${label}.station.list_ext
  mv Ts.${label}.station.list Ts.${label}.station.list_orig
  mv Ts.${label}.station.list.x Ts.${label}.station.list

echo 'adding population-flag and country code to data files'
  ${fortran_compile} addRSUcc.f -o addRSUcc.exe
  ./addRSUcc Ts.${label}

echo "Creating annual anomalies ANN.d$1.[1-6]"
./toANNanom Ts.${label}

${fortran_compile} PApars.f tr2.f t2fit.f -o PApars.exe
${fortran_compile}  flags.f               -o  flags.exe
${fortran_compile} padjust.f              -o padjust.exe

./PApars ${label}
./padjust Ts.${label}

./invnt.exe Ts.${label}.PA > Ts.${label}.PA.station.list

mv ANN* *x *ext Ts*bin* *exe *log* *use*  work_files/.
mv Ts* to_next_step/.    ; mv *list work_files/.
rm -f v2.inv
